<script setup>
import {reactive, ref} from 'vue'
import { emailValid, phoneValid } from '@/utils/validator';
import { ElMain, ElMessage ,ElMessageBox} from 'element-plus';


// 表格组件
const tableRef = ref(null)
// 表格数据
const accountInfoList = ref([])
// 弹窗表格组件实例
const dialogFormRef = ref(null)
const userInfo = ref([
    {
        "id": 1,
        "accountName": "Su Qiang",
        "accountRole": "教师",
        "phone": "13851746205",
        "email": "605213740@qq.com",
        "note": ""
    },
    {
        "id": 2,
        "accountName": "Sheng Xiang",
        "accountRole": "教师",
        "phone": "13951884545",
        "email": "rsheng81@163.com",
        "note": ""
    },
    {
        "id": 3,
        "accountName": "Wang Xiuyun",
        "accountRole": "教师",
        "phone": "13264632456",
        "email": "40456393@qq.com",
        "note": ""
    },
    {
        "id": 4,
        "accountName": "Xu Xinyu",
        "accountRole": "教师",
        "phone": "15266634325",
        "email": "morse - xu@hotmail.com",
        "note": ""
    },
    {
        "id": 5,
        "accountName": "教师 Li",
        "accountRole": "教师",
        "phone": "13996361815",
        "email": "xiaozhi9527.cy@outlook.com",
        "note": ""
    },
    {
        "id": 6,
        "accountName": "User6",
        "accountRole": "教师",
        "phone": "18934567890",
        "email": "user6@163.com",
        "note": ""
    },
    {
        "id": 7,
        "accountName": "User7",
        "accountRole": "教师",
        "phone": "13345678901",
        "email": "user7@gmail.com",
        "note": ""
    },
    {
        "id": 8,
        "accountName": "User8",
        "accountRole": "教师",
        "phone": "15567890123",
        "email": "user8@qq.com",
        "note": ""
    },
    {
        "id": 9,
        "accountName": "User9",
        "accountRole": "教师",
        "phone": "17789012345",
        "email": "user9@outlook.com",
        "note": ""
    },
    {
        "id": 10,
        "accountName": "User10",
        "accountRole": "教师",
        "phone": "19901234567",
        "email": "user10@163.com",
        "note": ""
    },
    {
        "id": 11,
        "accountName": "User11",
        "accountRole": "教师",
        "phone": "14412345678",
        "email": "user11@gmail.com",
        "note": ""
    },
    {
        "id": 12,
        "accountName": "User12",
        "accountRole": "教师",
        "phone": "16623456789",
        "email": "user12@qq.com",
        "note": ""
    },
    {
        "id": 13,
        "accountName": "User13",
        "accountRole": "教师",
        "phone": "18834567890",
        "email": "user13@outlook.com",
        "note": ""
    },
    {
        "id": 14,
        "accountName": "User14",
        "accountRole": "教师",
        "phone": "12245678901",
        "email": "user14@163.com",
        "note": ""
    },
    {
        "id": 15,
        "accountName": "User15",
        "accountRole": "教师",
        "phone": "15556789012",
        "email": "user15@gmail.com",
        "note": ""
    },
    {
        "id": 16,
        "accountName": "User16",
        "accountRole": "教师",
        "phone": "17767890123",
        "email": "user16@qq.com",
        "note": ""
    },
    {
        "id": 17,
        "accountName": "User17",
        "accountRole": "教师",
        "phone": "19978901234",
        "email": "user17@outlook.com",
        "note": ""
    },
    {
        "id": 18,
        "accountName": "User18",
        "accountRole": "教师",
        "phone": "13389012345",
        "email": "user18@163.com",
        "note": ""
    },
    {
        "id": 19,
        "accountName": "User19",
        "accountRole": "教师",
        "phone": "14490123456",
        "email": "user19@gmail.com",
        "note": ""
    },
    {
        "id": 20,
        "accountName": "User20",
        "accountRole": "教师",
        "phone": "16601234567",
        "email": "user20@qq.com",
        "note": ""
    },
    {
        "id": 21,
        "accountName": "User21",
        "accountRole": "教师",
        "phone": "18812345678",
        "email": "user21@outlook.com",
        "note": ""
    },
    {
        "id": 22,
        "accountName": "User22",
        "accountRole": "教师",
        "phone": "12223456789",
        "email": "user22@163.com",
        "note": ""
    },
    {
        "id": 23,
        "accountName": "User23",
        "accountRole": "教师",
        "phone": "15534567890",
        "email": "user23@gmail.com",
        "note": ""
    },
    {
        "id": 24,
        "accountName": "User24",
        "accountRole": "教师",
        "phone": "17745678901",
        "email": "user24@qq.com",
        "note": ""
    },
    {
        "id": 25,
        "accountName": "User25",
        "accountRole": "教师",
        "phone": "19956789012",
        "email": "user25@outlook.com",
        "note": ""
    },
    {
        "id": 26,
        "accountName": "User26",
        "accountRole": "教师",
        "phone": "13367890123",
        "email": "user26@163.com",
        "note": ""
    },
    {
        "id": 27,
        "accountName": "User27",
        "accountRole": "教师",
        "phone": "14478901234",
        "email": "user27@gmail.com",
        "note": ""
    },
    {
        "id": 28,
        "accountName": "User28",
        "accountRole": "教师",
        "phone": "16689012345",
        "email": "user28@qq.com",
        "note": ""
    },
    {
        "id": 29,
        "accountName": "User29",
        "accountRole": "教师",
        "phone": "18890123456",
        "email": "user29@outlook.com",
        "note": ""
    },
    {
        "id": 30,
        "accountName": "User30",
        "accountRole": "教师",
        "phone": "12201234567",
        "email": "user30@163.com",
        "note": ""
    }
]);

const selectRows = ref([])
// 当前页码
const currentPage = ref(1)
// 每页显示数量
const currentPagesize = ref(10)
// 弹窗的响应式绑定数据
const dialogForm = ref({
    "accountName": "",
    "accountRole": "",
    "phone": "",
    "email": "",
    "password":"",
    "note": ""
})
// 用户数据的总数
const userCount = ref(0)
// 弹窗选择账户角色
const accountRoles = reactive([
  {key:1,value:'管理员'},
  {key:2,value:'老师'}
])
// 校验规则具体
const validateField = {
  accountName: (rule, value, callback) => {
    if (!value) {
      callback(new Error('账户名称不能为空'));
    } else if (value.length > 100) {
      callback(new Error('姓名长度过长,请少于100个字符'));
    } else {
      callback();
    }
  },
  phone: (rule, value, callback) => {
    if (!value) {
      callback(new Error('电话号码不能为空'));
    } else if (!phoneValid(value)) {
      callback(new Error('电话号码格式不正确'));
    } else {
      callback();
    }
  },
  email: (rule, value, callback) => {
    if (!value) {
      callback(new Error('邮箱不能为空'));
    } else if (!emailValid(value)) {
      callback(new Error('邮箱格式不正确'));
    } else {
      callback();
    }
  },
  accountRole: (rule, value, callback) => {
    if (!value) {
      callback(new Error('账户角色不能为空'));
    } else if (value != '老师' && value != '管理员') {
      callback(new Error('账户角色无效'));
    } else {
      callback();
    }
  },
  remark: (rule, value, callback) => {
    if (value && value.length > 255) {
      callback(new Error('备注不能超过255个字符'));
    } else {
      callback();
    }
  },
  password:(rule,value,callback) => {
    if (!value) {
      callback(new Error('密码不能为空'));
    } else if (value.length < 8 || value.length > 20) {
      callback(new Error('密码长度必须在 8 到 20 位之间'));
    } else if (/[\u4e00-\u9fa5]/.test(value)) {
      callback(new Error('密码不能包含中文字符'));
    } else {
      const hasLetter = /[a-zA-Z]/.test(value);
      const hasNumber = /[0-9]/.test(value);
      const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(value);

      const validCount = [hasLetter, hasNumber, hasSpecialChar].filter(Boolean).length;
      if (validCount < 2) {
        callback(new Error('密码必须包含字母、数字和特殊字符中的至少两种'));
      } else {
        callback();
      }
    }
  }
};
// 弹窗表单校验规则
const dialogRules = {
  accountName:[
    {required:true,message:'请输入账户名称',trigger:'blur'},
    {validator:validateField.accountName,trigger:'blur'}

  ],
  accountRole:[
    {required:true,message:'请输入电话名称',trigger:'change'},
    {validator:validateField.accountRole,trigger:'blur'}

  ],
  phone:[
    {required:true,message:'请输入电话',trigger:'blur'},
    {validator:validateField.phone,trigger:'blur'}

  ],
  email:[
    {required:true,message:'请输入邮箱',trigger:'blur'},
    {validator:validateField.email,trigger:'blur'}

  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {validator:validateField.password,trigger:'blur'}
  ]

}
// 弹窗是否可见
const dialogFormVisible = ref(false)

// 弹窗标题
const currentDialogTitles = ref([
  {key:1,value:'修改账户/角色'},
  {key:2,value:'查看账户/角色'},
  {key:3,value:'创建账户/角色'}
])
// 当前弹窗类型
const currentDialogTitleIndex = ref(0)

// 清除选择
const clearAllSelection = () => {
  tableRef.value.clearSelection()
}
// 处理点击新增按钮
const handleAdd = () => {
  dialogFormVisible.value = true;
  currentDialogTitleIndex.value = 2;
}

//查看数据
const handleShow = (id) => {
  dialogForm.value = {...accountInfoList.value.find((item) => {return item.id === id})}
  dialogFormVisible.value = true;
  currentDialogTitleIndex.value = 1;
}
// 修改数据
const handleEdit =  (id) => {
  dialogForm.value = {...userInfo.value.find((item) => {return item.id === id})}
  dialogFormVisible.value = true;
  currentDialogTitleIndex.value = 0;

}


// 得到用户列表


// 多选删除
const handleDelByIds = () => {
  const ids = []
  selectRows.value.forEach((item) => {
    ids.push(item.id)
  })
  ElMessageBox.confirm('你确定要删除这些数据吗? 注意!此操作不可逆转')
    .then(() => {
        userInfo.value = userInfo.value.filter((item) => {
            return !ids.includes(item.id)
        })
        ElMessage.success('删除成功')
        tableRef.value.clearSelection()

    })

}


// 弹窗关闭前
const handleDialogClose = () => {
  Object.keys(dialogForm.value).forEach(key => {
    dialogForm.value[key] = ''
  })
  dialogForm.value.accountRole = 1

  dialogFormVisible.value = false
}


// 选择数据的处理
const handleSelectionChange = (selection) => {
    selectRows.value = selection
}

// 点击查看数据
const handleCheck = (id) => {
    
    dialogForm.value = {
        ...userInfo.value.find((item) => {
        return item.id === id
    })}
    dialogFormVisible.value = true
    currentDialogTitleIndex.value = 1;
}

// 删除数据
const handleDel = (id) => {
    ElMessageBox.confirm('你确定要删除这条数据吗? 注意!此操作不可逆转')
    .then(() => {
        userInfo.value = userInfo.value.filter((item) => {
            return item.id !== id
        })
        ElMessage.success('删除成功')
    }).catch(()=>{

    })
}

// 注册用户或者修改用户点击触发
const handleConfirm = () => {
    dialogFormRef.value.validate((valid) => {
        if (!valid) {
            return ElMessage.error("请填写正确的信息")
        }
        if (currentDialogTitleIndex.value == 2) {
          // 新增用户
          const obj = { ...dialogForm.value }
          obj.id = Date.now()
          userInfo.value.push(obj)
          ElMessage.success('新增成功')
          dialogFormVisible.value = false
        } else {
            // 修改用户
            const obj = userInfo.value.find((item) => {
                return item.id === dialogForm.value.id
            })
            obj.id = dialogForm.value.id
            obj.accountName = dialogForm.value.accountName
            obj.accountRole = dialogForm.value.accountRole
            obj.phone = dialogForm.value.phone
            obj.email = dialogForm.value.email
            obj.note = dialogForm.value.note
            ElMessage.success('修改成功')
            dialogFormVisible.value = false
        }
    })
    
}

</script>

<template>
    <div class="account-container">
      <!-- dialog -->
      <el-dialog v-model="dialogFormVisible" :title="currentDialogTitles[currentDialogTitleIndex].value" width="50%" :before-close="handleDialogClose">
        <el-form :model="dialogForm" :rules="dialogRules" :disabled="currentDialogTitleIndex === 1" ref="dialogFormRef">
          <el-form-item prop="accountName" label="账户名称">
            <el-input v-model="dialogForm.accountName" placeholder="请输入账户名称" autocomplete="off" size="default" style="width: 100%;"/>
          </el-form-item>
          <el-form-item prop="phone" label="电话">
            <el-input v-model="dialogForm.phone" autocomplete="off" placeholder="请输入电话" size="default" style="width: 100%;"/>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="dialogForm.email" autocomplete="off" placeholder="请输入邮箱" size="default" style="width: 100%;"/>
          </el-form-item>
          <el-form-item prop="accountRole" label="账户角色">
            <el-select v-model="dialogForm.accountRole" placeholder="请选择账户角色" size="default">
                <el-option v-for="item in accountRoles" :key="item.key" :label="item.value" :value="item.value">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="password" label="密码" v-if="currentDialogTitleIndex === 2">
            <el-input v-model="dialogForm.password" autocomplete="off"
            placeholder="请输入密码"
            size="default"
            style="width: 100%;"
            show-password
            type="password"/>
          </el-form-item>
          <el-form-item prop="note" label="备注" style="width:100%">
            <el-input v-model="dialogForm.note" type="textarea" size="large" style="width: 100%;" :rows="5"
            maxlength="255" show-word-limit
            placeholder="请输入备注信息"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false" size="default" >取消</el-button>
            <el-button type="primary" @click="handleConfirm" size="default" >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <div class="nav_show">首页/账户/角色管理</div>
      <div class="title">
        <h3>账户/角色管理</h3>
      </div>
      <div class="inp"  style="margin-bottom: 20px;">
        <div class="left">
          <el-button color="#1274b7" size="default"
          @click="handleAdd"
          >新增</el-button>
          <el-button
          :disabled="selectRows.length === 0"
          size="default"
           type="danger"
           @click="clearAllSelection">({{ selectRows.length }})取消选中</el-button>
           <el-button type="danger"  circle size="default" v-show="selectRows.length > 0" @click="handleDelByIds">
            <el-icon><Delete /></el-icon>
           </el-button>
        </div>
        <div class="right">
          <el-form   size="default" >
            <el-form-item><el-input  placeholder="请输入账户名称" size="default" ></el-input></el-form-item>
            <el-form-item><el-input  placeholder="请输入电话" size="default"></el-input></el-form-item>
            <el-form-item><el-input  placeholder="请输入邮箱" size="default" ></el-input></el-form-item>
          </el-form>
          <el-button type="primary" size="default">查询</el-button>
        </div>
      </div>
      <el-table ref="tableRef" style="width: 100%" :data="userInfo.slice((currentPage-1)*currentPagesize,currentPage*currentPagesize)" size="large" max-height="60vh" @selection-change="handleSelectionChange"
        :row-key="(row) => { return row.id }">
        <el-table-column type="selection" width="55" :reserve-selection="true"/>
        <el-table-column label="账户名称" width="120" prop="accountName"/>
        <el-table-column  label="账户角色" width="120" prop="accountRole"/>
        <el-table-column prop="phone" label="电话"  width="240" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="note" label="备注" />
        <el-table-column label="操作" align="center" min-width="120px">
          <template #default="{row}">
            <el-button size="small" @click="handleCheck(row.id)">
              <el-icon><View /></el-icon>
            </el-button>
            <el-button
              size="small" @click="handleEdit(row.id)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button
              size="small" @click="handleDel(row.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page_box">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="currentPagesize"
            :page-sizes="[10,15,20]"
            size="large"
            layout="total, prev, pager, next, sizes,jumper"
            :total="userInfo.length"
            />
      </div>
    </div>
</template>

<style scoped lang="less">
.account-container {
  padding: 20px;
  background-color: #fff;
  .title {
    margin-top: 20px;
    margin-bottom: 20px;
    h3 {
      font-weight: normal;
    }
  }

}

.inp {
  display: flex;
  justify-content: space-between;
  .right {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
  ::v-deep .is-disabled {
    background-color: #f5f5f5;
    border: none;
  }
}

 .el-table {
  margin-top: 20px;
}

::v-deep .el-table__header th{
   color: black;
}

::v-deep .el-table {
  .el-button {
    border: none;
    font-size: 20px;
    background-color: transparent;
  }
}

::v-deep .row-highLight {
  background-color: #e6f4ff !important;
}

::v-deep .no-hover:hover > td {
  background-color: #e6f4ff  !important;
}





// dialog
.el-dialog {
  .el-form  {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  .el-form-item  {
    display: block;
    width: 45%;
  }


}

::v-deep .el-form-item__label {
    font-size: 15px;
    color: black;
  }
::v-deep .el-textarea .el-input__count {
    bottom: -15px;
  }

  // 查询
  .right {
    .el-form{
      display: flex;
    }
  }

  .page_box {
    margin-top: 20px;
    display: flex;
    width: 100%;
    justify-content: center;
  }
</style>
